package com.suyang.syt.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.suyang.syt.auth.AuthClass;
import com.suyang.syt.auth.AuthMethod;
import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.util.JsonUtil;
import com.suyang.syt.util.VideoImageUtil;

@Controller
@RequestMapping("/admin/fileUpload")
@AuthClass
public class AdminFileUploadController {

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@AuthMethod
	public void upload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IOException {
		String uploadPath = request.getParameter("uploadPath");
		int width = 0;
		int height = 0;
		if ("logo".equals(uploadPath)) {
			width = 89;
			height = 89;
		} else if ("banner".equals(uploadPath)) {
			width = 140;
			height = 140;
		}
		PrintWriter printWriter = response.getWriter();
		if (file == null) {
			printWriter.write(JsonUtil.toJson(new AjaxObj(0, "请选择文件后上传!")));
			printWriter.flush();
			printWriter.close();
			return;
		}
		try {
			String uploadDir = BeanFactoryContext.getRealPath() + "/resources/upload/" + uploadPath + "/";
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
			// 此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
			// String newFileName = System.currentTimeMillis() +
			// file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String newFileName = System.currentTimeMillis() + ".png";
			// FileUtils.copyInputStreamToFile(file.getInputStream(), new
			// File(uploadDir, newFileName));
			Thumbnails.of(file.getInputStream()).size(width, height).outputFormat("png").toFile(uploadDir + "/" + newFileName);
			printWriter.write(JsonUtil.toJson(new AjaxObj(1, "上传成功", newFileName)));
			printWriter.flush();
			printWriter.close();
			return;
		} catch (Exception e) {
			printWriter.write(JsonUtil.toJson(new AjaxObj(0, "上传文件失败!")));
			printWriter.flush();
			printWriter.close();
		}
	}

	@SuppressWarnings("static-access")
	@RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
	@AuthMethod
	public void uploadVideo(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IOException {
		String uploadPath = request.getParameter("uploadPath");
		PrintWriter printWriter = response.getWriter();
		if (file == null) {
			printWriter.write(JsonUtil.toJson(new AjaxObj(0, "请选择视频后上传!")));
			printWriter.flush();
			printWriter.close();
			return;
		}
		try {
			String uploadDir = BeanFactoryContext.getRealPath() + "/resources/upload/" + uploadPath + "/";
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			String newFileName = System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadDir, newFileName));
			printWriter.write(JsonUtil.toJson(new AjaxObj(1, "上传成功", newFileName)));
			printWriter.flush();
			printWriter.close();
			// 保存视频截图
			// 1.获取当前工程目录,获取ffmpeg.exe
			File directory = new File(".");
			String root = directory.getCanonicalPath();
			String ffmpegPath = root + "/src/main/webapp/resources/tools/ffmpeg/ffmpeg.exe";
			String newFileNames = newFileName.substring(0, newFileName.indexOf('.')) + ".png";
			String imagepath = uploadDir + "/" + newFileNames;// 图片路径
			uploadDir = uploadDir + "/" + newFileName;// 视频路径
			// boolean flag= VideoImageUtil.getVideoImage(ffmpegPath, uploadDir,
			// imagepath);
			VideoImageUtil.getVideoImage(ffmpegPath, uploadDir, imagepath);
			// 上传视频与前台获取照片之间有时间差，所以为了保证前台能及时获取照片显示，这里设计让上传之后文件睡0.2s
			new Thread().sleep(100);
			// 视频截图结束
			return;

		} catch (Exception e) {
			printWriter.write(JsonUtil.toJson(new AjaxObj(0, "上传视频文件失败!")));
			printWriter.flush();
			printWriter.close();
		}
	}

	@RequestMapping(value = "/weixin", method = RequestMethod.POST)
	@AuthMethod
	public void uploadWeixin(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IOException {
		String type = request.getParameter("type");
		PrintWriter printWriter = response.getWriter();
		if (file == null) {
			printWriter.write(JsonUtil.toJson(new AjaxObj(0, "请选择文件后上传!")));
			printWriter.flush();
			printWriter.close();
			return;
		}
		try {
			String uploadDir = BeanFactoryContext.getRealPath() + "/resources/upload/weixin";
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			String newFileName = "";
			String newFile = "";
			if ("image".equals(type)) {
				newFileName = System.currentTimeMillis() + ".png";
				newFile = uploadDir + "/" + newFileName;
				Thumbnails.of(file.getInputStream()).size(300, 300).outputFormat("png").toFile(newFile);
			} else if ("thumb".equals(type)) {
				newFileName = System.currentTimeMillis() + ".png";
				newFile = uploadDir + "/" + newFileName;
				Thumbnails.of(file.getInputStream()).size(48, 48).outputFormat("png").toFile(newFile);
			} else if ("voice".equals(type) || "video".equals(type)) {
				String originalFilename = file.getOriginalFilename();
				newFileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
				newFile = uploadDir + "/" + newFileName;
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(newFile));
			} else if ("imageText".equals(type)) {
				newFileName = System.currentTimeMillis() + ".png";
				newFile = uploadDir + "/" + newFileName;
				Thumbnails.of(file.getInputStream()).size(200, 200).outputFormat("png").toFile(newFile);
			}
			printWriter.write(JsonUtil.toJson(new AjaxObj(1, "成功", newFileName)));
			printWriter.flush();
			printWriter.close();
			return;
		} catch (Exception e) {
			printWriter.write(JsonUtil.toJson(new AjaxObj(0, "上传文件失败!")));
			printWriter.flush();
			printWriter.close();
		}
	}

}
